<?php
class Contact extends Frontend_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->library('form_validation');
		$this->load->Model(array("Mcontact","Marticle"));
	}	
	
	public function index(){
		$data['detail'] = $this->Marticle->showArticleById(1);
		$data['title'] = $data['detail']['title'];
		$data['keywords'] = $data['detail']['keywords'];
		$data['description'] = $data['detail']['description'];
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$this->form_validation->set_rules('subject', 'tiêu đề', 'required|xss_clean');
			$this->form_validation->set_rules('fullname', 'tên đầy đủ', 'required|xss_clean');
	        $this->form_validation->set_rules('email', 'địa chỉ email', 'required|valid_email');
	        $this->form_validation->set_rules('phone', 'điện thoại', 'required|numeric');
	        $this->form_validation->set_rules('message', 'tin nhắn', 'required');

	        if ($this->form_validation->run() == FALSE) {
	        	$error = validation_errors();
				$error = explode("\n",$error);
				foreach($error as $err){
					if($err != ""){
           				$data['errors'][] = $err;
					}
				}
	        }else{
	        	$subject = $this->input->post('subject');
	            $fullname = $this->input->post('fullname');
				$email = $this->input->post('email');
				$phone = $this->input->post('phone');
				$message = $this->input->post('message');

				$data_insert = array(
					'subject' => $this->db->escape_str($subject),
					'fullname' => $this->db->escape_str($fullname),
					'email' => $this->db->escape_str($email),
					'phone' => $this->db->escape_str($phone),
					'message' => $this->db->escape_str($message),
					'created_at' => time() 
				);
				$this->Mcontact->insert($data_insert);
				$this->session->set_flashdata(array("success"=>trans('message_send_successfully')));
				redirect(base_url());
	        }
		}
		$this->parser->parse("contact/index.tpl", NULL, $data);
	}
}